// logs.js
const {DevLink} = require('../../utils/devs.js')
const app = getApp()
const link = new DevLink("android")

Page({
  timer: null,
  data: {
    devs: []
  },
  onShow() {
    if (!app.globalData.devs) {
      app.globalData.devs = wx.getStorageSync('devs') || []
    }
    let data = app.globalData.devs;
    for (let i=0; i<data.length; i++) {
      let odev = this.dev(data[i].mac)
      if (odev) {
        data[i] = odev
      } else {
        data[i].value = 0
        data[i].online = 0
        data[i].sw1 = 0
        data[i].ad1 = 0
        data[i].register = false
        data[i].pending = true
      }
    }
    console.log("dev-ui", data)
    this.setData({"devs": data})
    this.timer = setInterval(()=>this.onTimer(), 1000)
  },
  onHide() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = undefined
    }
  },
  onLoad() {
    app.globalData.devs = wx.getStorageSync('devs')
    link.onCloseNotify(()=>{
      let devs = this.data.devs
      for (let i =0; i<devs.length; ++i) {
        devs[i].register = false
        devs[i].pending = true
        devs[i].online = 0
      }
    })
    link.onDevInfo((x)=>this.onDevInfo(x))
    link.start()
  },
  dev(mac) {
    let devs = this.data.devs
    for (let i =0; i<devs.length; ++i) {
      if (devs[i].mac == mac)  return devs[i];
    }
    return null
  },
  refresh() {
    let devs = this.data.devs
    this.setData({devs})
  },
  register(macList) {
    link.write(macList)
  },
  onSwitch({detail, target}) {
    let mac = target.dataset.mac
    let dev = this.dev(mac)
    if (!dev || dev.pending || !dev.online || !link.valid)  return
    dev.sw1 = detail.value?1:0
    dev.pending = true
    this.refresh()
    link.write({mac, 'code':21, 'val': dev.sw1})
  },
  onTimer() {
    let macs = this.data.devs.filter(x=>!x.register).map(x=>x.mac)
    macs && macs.length && this.register(macs)
  },
  onDevInfo(x) {
    let r = JSON.parse(x)
    if (r instanceof Array) {
      /*
      enum {
	C_LOGIN = 1,
	C_RESTART = 2,
	C_AD1   = 10,
	C_AD2   = 11,
	C_AD3   = 12,
	C_SW1   = 21,
	C_SW2   = 22,
};
      */
      r.forEach(x=>{
        let dev = this.dev(x.mac)
        if (!dev)  return
        if (x.code == 1) dev.online = x.val
        else if (x.code == 10) dev.ad1 = x.val
        else if (x.code == 21) dev.sw1 = x.val
        dev.register = true
        dev.pending = false
      })
      this.refresh()
    }
  }

})
